/**
 * Created by levy on 16/7/6.
 */
import TextArea from "../components/form/TextArea";
import DatePicker from "../components/form/DatePicker";
import BlockBtn from "../components/detail/BlockBtn";
import FooterBtn from "../components/detail/FooterBtn";
import Swiper from "../components/Swiper";
import BottomForm from "../components/detail/BottomForm";
import SelectPerson from "../components/detail/SelectPerson";
import LargeImg from "../components/LargeImg";

const lf = liefeng,
    R = React,
    RC = React.createClass,
    log = lf.utils.log,
    ajax = lf.utils.ajax,
    api = lf.api.worktable,
    EXECUTOR = 'executor',
    CC = 'ccPerson'; //抄送

let ajaxData = {
    [EXECUTOR]: '',
    [CC]: '',
};


const Root = RC({
    getInitialState() {
        return {
            imgList: [],
            formVisible: '',
            selectFlag: '',
            selectUserType: 1, //1 执行人; 3 抄送人
            largeImgSrc: '',
        }
    },
    componentDidMount() {
        R.findDOMNode(this.refs.upLoadBtn).addEventListener('tap', () => {
            lf.appJs.selectPhoto(9);
        });

        lf.appJs.registerHandler('getPhotoFromApp', (data) => {
            //这里也许应该封装一下 TODO
            var imgList = this.state.imgList;

            data.indexOf(',') != -1 && data.split(',').map( function ( item ) {
                imgList.unshift(item);
            });
            data.indexOf(',') == -1 && imgList.unshift(data);

            if (imgList.length > 9) {
                alert('最多只能上传9张图片!');
                return;
            }
            this.setState({imgList: imgList});
        });
    },
    render() {
        let st = this.state,
            footerBtn = [{aLinkClass: 'green ', clickHandler: this.submit, text: '确定'}],
            formFooterBtn = [{aLinkClass: 'red ', clickHandler: this.hideSelect, text: '取消'},
                {aLinkClass: 'green ', clickHandler: this.confirmSelect, text: '确定'}];

        //表单弹出内容
        const formItemRender = () => {
            return <SelectPerson method={api.getDailyWorkStaff}
                                 userType={st.selectUserType} />
        };

        //TODO 上传图片的后面封装成组件。它的样式先不要动
        return (<div className="daily-work-add">
            <div className="task-desc mission-group">
                <p className="line-title">任务描述</p>
                <TextArea addClass="input-text" placeholder="限200字 (必填)" name="content"/>
            </div>
            <div className="mission-group">
                <DatePicker name="endTime" addClass="choose-time"/>
            </div>
            <div className="bottom-form-handle-img">
                <a className="up-load-img-btn" ref="upLoadBtn" href="javascript:">上传图片</a>
                <Swiper imgList={this.state.imgList}
                                 deleteFn={this.deleteImg}
                                 enlargeHandler={this.enlargeHandler}
                                 floatFlag={false} />
            </div>
            <BlockBtn data={{tit:"执行人(必填)", default: '限1人',
                    selectHandler: this.showSelect, selectFlag: EXECUTOR}}/>
            <BottomForm visible={st.formVisible} footerBtn={formFooterBtn}
                    itemRender={formItemRender}/>
            <FooterBtn data={footerBtn}/>
            <LargeImg src={st.largeImgSrc}/>
        </div>)

        //暂时屏蔽抄送人
        // <BlockBtn data={{tit:"抄送人(选填)", default: '限3人', selectHandler: this.showSelect, selectFlag: CC}}/>

    },
    //TODO 准备封装,代码重复了
    deleteImg(e) {
        let $node = $(e.target),
            $img = $node.siblings('img'),
            imgList = this.state.imgList;

        for(let i = 0; i < imgList.length; i++) {
            let img = imgList[i];
            if(img == $img.attr('src')) {
                imgList.splice(i,1);
                break;
            }
        }

        this.setState({
            imgList: imgList
        });
    },
    enlargeHandler(src) {
        this.setState({largeImgSrc: src});
    },
    showSelect(flag) {
        this.setState({
            formVisible: 'this',
            selectFlag: flag,
            selectUserType: flag == EXECUTOR ? 1 : 3, //1 执行人; 3 抄送人
        });
    },
    hideSelect() {
        this.setState({formVisible: ''});
    },
    confirmSelect() {
        let $selected = $('.text-dot.choose'),
            $text = $('.text-before-arrow'),
            name;

        if(this.state.selectFlag == CC) {
            ajaxData[CC] = $selected.data('id');

            name = $selected.text();
            $text.eq(1).text(name);
        }
        else {
            ajaxData[EXECUTOR] = $selected.data('id');

            name = $selected.text();
            $text.eq(0).text(name);
        }

        this.hideSelect();
    },
    submit() {
        var me = this;

        let content = $('#content').val(),
            endTime = $('#endTime').val(),
            pic = $('.swiper-activity-img > img'),
            pics = [];

        if(!content) {
            alert('请填写任务描述');
            return;
        }else if(content.length > 200){
            alert('填写不能超过200字');
            return;
        }

        if(!endTime){
            alert('请选择时间');
            return;
        }

        //判定时间是否超前
        var date = endTime;

        date = date.substring(0,19);
        date = date.replace(/-/g,'/');

        var timestamp = new Date(date).getTime(),
            nowTimestamp = Date.parse(new Date());

        if(timestamp < nowTimestamp){
            alert('截止时间不得小于当前时间');
            return;
        }

        if(!ajaxData[EXECUTOR]) {
            alert('请选择执行人');
            return;
        }

        for(var i = 0;i<pic.length;i++){
            pics[i] = pic.eq(i).attr('src');
        }

        var createUpload = function (url) {
            var pics = url.split(","),
                imgMessage = '';

            for(var i = 0;i<pics.length;i++){
                imgMessage = imgMessage + pics[i] + ',,|'
            }

            var data = {
                creatorId: me.props.user.id,
                content: content,
                endTime: endTime + ':00',
                sponsorId: ajaxData[EXECUTOR],
                senderId: ajaxData[CC],
                imgMessage: imgMessage,
            }

            me.createMission(data);

        }

        if(pic.length == 0){

            var data = {
                creatorId: me.props.user.id,
                content: content,
                endTime: endTime + ':00',
                sponsorId: ajaxData[EXECUTOR],
                senderId: ajaxData[CC],
            }

            me.createMission(data);

        }else{
            lf.bridgeJs.uploadImg(pics.toString(),createUpload);
        }

    },
    createMission(data){
        ajax({
            type: 'post',
            data: data
        },api.createDailyWork, () => {
            debugAlert('success');
            alert('新建任务成功!', () => lf.appJs.doClose());
        });
    },
});

lf.appJs.getUser(function (user) {
    R.render(<Root user={user}/>, document.getElementById('root'));
});
